<?php

namespace app\admin\controller\fastflow;

use app\admin\model\Admin;
use app\admin\model\fastflow\flow\EbillCopy;
use app\admin\model\fastflow\Signature;
use app\common\controller\Backend;
use fastflow\api;
use think\Loader;
use think\Session;

/**
 * 我的抄送
 *
 * @icon fa fa-circle-o
 */
class Carbon extends Backend
{

    protected $noNeedRight = ['bill', 'detail', 'exportWord'];
    /**
     * Carbon模型对象
     * @var \app\admin\model\fastflow\Carbon
     */
    protected $model = null;

    public function _initialize()
    {
        $this->model = new \app\admin\model\fastflow\Carbon;
        parent::_initialize();
    }

    public function bill()
    {
        $billModel = new \app\admin\model\fastflow\flow\Bill;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $billModel
                ->where($where)
                ->order($sort, $order)
                ->count();

            $list = $billModel
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            foreach ($list as &$row) {
                $row['carbons'] = 0;
            }

            if ($total > 0) {
                $carbon_list = $this->model->where(['receiver_id' => Session::get()['admin']['id'], 'is_read' => 0])->select();
                foreach ($carbon_list as $item) {
                    for ($i = 0; $i < count($list); $i++) {
                        if ($item['bill'] == $list[$i]['bill_table']) {
                            $list[$i]['carbons'] += 1;
                            break;
                        }
                    }
                }
            }


            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch('index');
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        //4.4.2 获取单据列表
        $billModel = new \app\admin\model\fastflow\flow\Bill;
        $bill_list = $billModel->field(['bill_table'])->select();
        $table_list = [];
        foreach ($bill_list as $bill) {
            $table_list[] = $bill['bill_table'];
        }
        //4.4.2 !-- 
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->where($where)
                ->where('receiver_id', Session::get()['admin']['id'])
                //4.4.2 过滤已删除单据数据
                ->where('bill', 'in', $table_list)
                //4.4.2 !--
                ->order($sort, $order)
                ->paginate($limit);

            $all = $this->model->where('receiver_id', Session::get()['admin']['id'])->select();
            $read_count = 0;
            $unread_count = 0;
            foreach ($all as $item) {
                if ($item['is_read'] == '0') {
                    $unread_count += 1;
                } else {
                    $read_count += 1;
                }
            }

            $result = array("total" => $list->total(), "rows" => $list->items(), "extend" => ['read' => $read_count, 'unread' => $unread_count, 'all' => count($all)]);

            return json($result);
        } elseif ($this->request->isGet()) {
            $today_rows = $this->model
                ->where('receiver_id', Session::get()['admin']['id'])
                ->whereTime('sendtime', 'today')
                //4.4.2 过滤已删除单据数据
                ->where('bill', 'in', $table_list)
                //4.4.2 !--
                ->select();
            $bg_color = ['danger', 'info', 'success', 'warning'];
            foreach ($today_rows as &$row) {
                $rand = rand(0, 3);
                $row['bgColor'] = $bg_color[$rand];
                $sender_row = Admin::find($row['sender_id']);
                if ($sender_row) {
                    $row['sender'] = $sender_row['nickname'];
                } else {
                    $row['sender'] = 'ID:' . $row['sender_id'];
                }
            }
            rsort($today_rows);
            $today_str = date('Y-m-d');
            $today_range = $today_str . ' 00:00:00 - ' . $today_str . ' 23:59:59';
            $this->view->assign(['todayRows' => $today_rows, 'todayCount' => count($today_rows), 'todayRange' => $today_range]);
            return $this->view->fetch();
        }
    }

    /**
     * 查看详情
     */
    public function detail()
    {
        $params = input('');
        if (!isset($params['id'])) {
            return '参数错误';
        }
        $id = $params['id'];
        $row = $this->model->find($id);
        if (!$row) {
            return '未查询到抄送数据';
        }

        $row['is_read'] = 1;
        $row->save();

        $api = new api();
        $thread_logs = $api->getLogByIds($row['bill'], $row['bill_id'], explode(',', $row['thread_log_ids']));
        if (!$thread_logs) {
            return '未查询到审批数据';
        }
        $bill = \app\admin\model\fastflow\flow\Bill::where(['bill_table' => $row['bill']])->find();
        $bill_name = '';
        if ($bill) {
            $bill_name = $bill['bill_name'];
        }

        $bill_row = $api->getBillRow($row['bill'], $row['bill_id']);

        $initiator = '';
        if ($bill_row) {
            $initiator_id = $bill_row['initiator_id'];
            $admin = Admin::find($initiator_id);
            if ($admin) {
                $initiator = $admin['nickname'];
            }
        }
        $bill_row_url = http_build_query(['row' => $bill_row]);
        $domain = $_SERVER['HTTP_HOST'];

        $ebill_copy_id = $this->getEbillCopyId($row['bill'], $row['bill_id']);
        //查询是否有发起签章
        $hasSignature = false;
        $pdfFile = '';
        $signature = (new Signature())->where(['bill' => $row['bill'], 'bill_id' => $row['bill_id']])->find();
        if ($signature) {
            $hasSignature = true;
            $pdfFile = $signature['pdf_file'];
        }

        $this->view->assign(['bill' => $bill_name, 'bill_id' => $row['bill_id'], 'initiator' => $initiator, 'logs' => $thread_logs, 'ebill_id' => $ebill_copy_id, 'hasSignature' => $hasSignature, 'pdfFile' => $pdfFile]);
        $this->assignconfig([
            'domain' => $domain,
            'bill' => $row['bill'],
            'bill_id' => $row['bill_id'],
            'controller_url' => $this->getBillControllerUrl($row['bill']),
            'ebill_id' => $ebill_copy_id,
            'bill_row' => $bill_row_url,
            'hasSignature' => $hasSignature,
        ]);

        return $this->view->fetch();
    }

    public function exportWord()
    {
        if ($this->request->isAjax()) {
            \think\Loader::addNamespace('PhpOffice\PhpWord', ADDON_PATH . 'fastflow' . DS . 'library' . DS . 'PHPWord-master' . DS . 'src' . DS . 'PhpWord' . DS);
            \think\Loader::addNamespace('Laminas\Escaper', ADDON_PATH . 'fastflow' . DS . 'library' . DS . 'laminas-escaper' . DS . 'src' . DS);
            $api = new api();
            $row = $this->model->find(input('carbon_id'));
            if (!$row) {
                return ['code' => 0, 'msg' => '参数错误'];
            }
            $thread_logs = $api->getLogByIds($row['bill'], $row['bill_id'], explode(',', $row['thread_log_ids']));
            if (!$thread_logs) {
                return ['code' => 0, 'msg' => '参数错误'];
            }

            $dir = __DIR__ . DS . '..' . DS . '..' . DS . '..' . DS . '..' . DS . 'addons' . DS . 'fastflow' . DS . 'template' . DS;
            $detailTemplate = $dir . 'detail_table_tpl.docx';
            $docPath = 'detail_table.docx';
            $templateProcessor = new \PhpOffice\PhpWord\TemplateProcessor($detailTemplate);

            $bill = \app\admin\model\fastflow\flow\Bill::where(['bill_table' => input('bill')])->find();
            $bill_name = '';
            if ($bill) {
                $bill_name = $bill['bill_name'];
            }
            $bill_row = $api->getBillRow(input('bill'), input('bill_id'));
            $initiator = '';
            if ($bill_row) {
                $initiator_id = $bill_row['initiator_id'];
                $admin = Admin::find($initiator_id);
                if ($admin) {
                    $initiator = $admin['nickname'];
                }
            }

            $start_time = '';
            $log_list = [];
            foreach ($thread_logs as $day_logs) {
                foreach ($day_logs as $log) {
                    $log_list[] = $log;
                    if ($log['check_type'] == '5') {
                        $start_time = $log['createtime'];
                    }
                }
            }

            $values = [
                'bill' => $bill_name,
                'initiator' => $initiator,
                'starttime' => $start_time,
                'bill_id' => $bill_row['id'],
            ];
            $templateProcessor->setValues($values); //传值

            $domain = $_SERVER['HTTP_HOST'];
            $check_typp = ['1' => '同意', '2' => '驳回', '3' => '会签', '4' => '终止', '5' => '发起', '6' => '结束'];

            $rows = [];
            foreach ($log_list as $log) {
                $rows[] = [
                    'longtime' => $log['createtime'],
                    'step_name' => $log['step_name'],
                    'worker_name' => $log['worker_name'],
                    'check_type' => $check_typp[$log['check_type']],
                    'check_content' => $log['check_content'],
                    'file' => $log['file'] == '' ? '' : $log['file_name'] . $domain . $log['file'],
                    'agent' => $log['agent'],
                    'principal' => $log['principal']
                ];
            }
            $templateProcessor->cloneRowAndSetValues('longtime', $rows);
            $templateProcessor->saveAs($docPath);
            return ['code' => 1, 'msg' => '', 'data' => ['url' => '/detail_table.docx']];

        }
    }

    private function getBillControllerUrl($bill)
    {
        $flowBillRow = (new \app\admin\model\fastflow\flow\Bill())->where(['bill_table' => $bill])->find();
        $url = Loader::parseName($flowBillRow['controller'], 0);
        $url = str_replace('/_', '/', $url);
        return $url;
    }

    private function getEbillCopyId($bill, $bill_id)
    {
        $ebill_copy = (new EbillCopy())->where(['bill' => $bill, 'bill_id' => $bill_id])->find();
        if ($ebill_copy) {
            $ebill_copy = $ebill_copy->toArray();
            return $ebill_copy['id'];
        }
        return null;
    }


}
